package com.et.book.views;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;

import com.et.book.fenghuangchi.R;
import com.et.book.services.BookService;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.text.style.BulletSpan;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.Toast;
/**
 * 这是一个自定义view，用来显示图书内容，分上一页下一页
 * @author tao
 *
 */
public class BookView extends View implements OnGestureListener{
	/**
	 * 移动超过这么多则不响应点击事件
	 */
	public static final int MOVEOFFSET = 20;
	
	public static final int MOTION_ING = 1;
	public static final int MOTION_END = 2;
	
	public static final int BUILD_PAGE_LAST = 1;
	/**
	 * 绘制下一页
	 */
	public static final int BUILD_PAGE_NEXT = 2;
	public static final int BUILD_NONE = 0;
	/**
	 * 当前页
	 */
	private Bitmap currentPage = null;
	/**
	 * 下一页
	 */
	private Bitmap nextPage = null;
	
	private Canvas currentCanvas = null;
	private Canvas nextCanvas = null;
	
	private Scroller scroller = null;
	
	private BookService service = null;
	
	public int currentPageNumber = 0;
	/**
	 * x方向的偏移量
	 */
	private float offsetX = 0;
	
	private float touchDownX = 0;
	private float lastMoveX = 0;
	/**
	 * 当前的动画状态
	 */
	private int currentState = 0;
	
	private int currentBuildState = BUILD_NONE;
	/**
	 * 是否移动过
	 */
	private boolean hasMoved = false;
	
	private Handler handler = null;
	
	private ProgressDialog pd = null;
	
	private GestureDetector detector = null;
	
	public BookView(Context context) {
		super(context);
		scroller = new Scroller(context, new  AccelerateInterpolator());
		init();
	}

	public BookView(Context context, AttributeSet attrs) {
		super(context, attrs);
		scroller = new Scroller(context, new  AccelerateInterpolator());
		init();
	}

	public BookView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		scroller = new Scroller(context, new  AccelerateInterpolator());
		init();
	}

	private void init(){
		detector = new GestureDetector(getContext(), this);
		initHandler();
	}
	
	private void initHandler(){
		handler = new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				if (msg.what == 1) {
					try {
						service.gotoPage(currentPageNumber);
						service.drawPage(currentCanvas);
						service.nextPage();
						service.drawPage(nextCanvas);
						service.prePage();
						postInvalidate();
					} catch (Exception e) {
					}
					if (pd!=null) {
						pd.dismiss();
						pd = null;
					}
					return true;
				}
				
				return false;
			}
		});
	}
	
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		
		if (currentPage == null) {
			currentPage = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.RGB_565);
			currentCanvas = new Canvas(currentPage);
		}
		
		if (nextPage == null) {
			nextPage = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.RGB_565);
			nextCanvas = new Canvas(nextPage);
		}
		
		if (service == null) {
			service = new BookService(getMeasuredWidth(), getMeasuredHeight(), getContext());
			pd = ProgressDialog.show(getContext(), "", getContext().getResources().getString(R.string.initdata));
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Looper.prepare();
					service.openbook();
					Message msg = Message.obtain(handler);
					msg.what = 1;
					msg.sendToTarget();
					Looper.myLooper().quit();
				}
			}).start();
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		if (nextPage!=null) {
			canvas.drawBitmap(nextPage, 0, 0, null);
		}
		
		if (currentPage!=null) {
			canvas.save();
			canvas.translate(offsetX, 0);
			canvas.drawBitmap(currentPage, 0, 0, null);
			canvas.restore();
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		detector.onTouchEvent(event);
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:{
			if (!scroller.isFinished()) {
				scroller.abortAnimation();
			}
			hasMoved = false;
			currentBuildState = BUILD_NONE;
			touchDownX = event.getX();
			lastMoveX = 0;
			break;
		}
			
		case MotionEvent.ACTION_MOVE:{
			
			lastMoveX = event.getX() - touchDownX;
			if (Math.abs(lastMoveX)>MOVEOFFSET) {
				hasMoved = true;
			}
			postInvalidate();
			break;
		}
		
		case MotionEvent.ACTION_UP:{
			if (!hasMoved) {
				int x = (int)event.getX();
				if (x>getMeasuredWidth()/2) {
					if (service.islastPage()) {
						Toast.makeText(getContext(), "已经到最后一页了！",  Toast.LENGTH_SHORT).show();
					}else {
						try {
							service.nextPage();
							service.drawPage(nextCanvas);
						} catch (Exception e) {
						}		
						startMotion(0, -getMeasuredWidth());
					}
				}else {
					if (service.isfirstPage()) {
						Toast.makeText(getContext(), "已经是第一页了！",  Toast.LENGTH_SHORT).show();
					}
					else {
						try {
							service.prePage();
							service.drawPage(nextCanvas);
						} catch (Exception e) {
						}
						startMotion(0, getMeasuredWidth());
					}
				}
			}
			break;
		}

		default:
			break;
		}
		return true;
	}
	
	private void startMotion(int startX, int dx){
		currentState = MOTION_ING;
		scroller.startScroll(startX, 0, dx, 0, 350);
		postInvalidate();
	}
	
	@Override
	public void computeScroll() {
		super.computeScroll();
		
		if (scroller.isFinished()&&currentState == MOTION_ING) {
			currentState = MOTION_END;
			offsetX = 0;
			lastMoveX = 0;
			currentCanvas.drawBitmap(nextPage, 0,0, null);
		}
		
		if (scroller.computeScrollOffset()) {
			offsetX = scroller.getCurrX();
			postInvalidate();
		}
	}
	
	@Override
	protected void onAttachedToWindow() {
		SharedPreferences sp = getContext().getSharedPreferences("pagenumber", Context.MODE_PRIVATE);
		currentPageNumber = sp.getInt("page", 0);
		super.onAttachedToWindow();
	}
	
	@Override
	protected void onDetachedFromWindow() {
		SharedPreferences sp = getContext().getSharedPreferences("pagenumber", Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		try {
			service.nextPage();
		} catch (Exception e) {
		}
		
		editor.putInt("page", service.getCurrentPage());
		editor.commit();
		super.onDetachedFromWindow();
	}
	
	public void gotoPage(int page){
		try {
			service.gotoPage(page);
			service.drawPage(currentCanvas);
			service.nextPage();
			service.drawPage(nextCanvas);
			service.prePage();
		} catch (Exception e) {
		}
		postInvalidate();
	}
	
	public int getCurrentPage(){
		return service.getCurrentPage();
	}
	
	public int getToatalPage(){
		return service.getToatalPage();
	}
	
	public String getCurentPecent(){
		return service.getCurentPecent();
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}
	
	public boolean onFling(MotionEvent ev1, MotionEvent ev2, float arg2, float arg3) {
		float startx = ev1.getX();
		float endx = ev2.getX();
		
		if (startx>=endx) {
			if (service.islastPage()) {
				Toast.makeText(getContext(), "已经到最后一页了！",  Toast.LENGTH_SHORT).show();
			}else {
				try {
					service.nextPage();
					service.drawPage(nextCanvas);
				} catch (Exception e) {
				}		
				startMotion(0, -getMeasuredWidth());
			}
		}else {
			if (service.isfirstPage()) {
				Toast.makeText(getContext(), "已经是第一页了！",  Toast.LENGTH_SHORT).show();
			}
			else {
				try {
					service.prePage();
					service.drawPage(nextCanvas);
				} catch (Exception e) {
				}
				startMotion(0, getMeasuredWidth());
			}
		}
		return true;
	}
	
	@Override
	public void onLongPress(MotionEvent e) {
		
	}
	
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}
	
	@Override
	public void onShowPress(MotionEvent e) {
		
	}
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}
}
